#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/9/27 18:23
# @Author  : youfeng
import os
import sys

import psutil


class RunTime(object):

    def __init__(self, log):
        self.log = log
        self.__base_path = self.__get_file_path()
        self.__file_name = self.__get_file_name()
        self.__pid_file_name = '.{}.pid'.format(self.__file_name)
        self.log.info("pid文件路径: base_path = {}".format(self.__base_path))
        self.log.info("pid文件名称: pid_name = {}".format(self.__pid_file_name))

        self.__make_pid_file()

    def __del__(self):
        self.__del_pid_file()

    @staticmethod
    def __get_file_name():
        file_name = sys.argv[0].split("/")[-1].split(".")[0]
        return file_name

    @staticmethod
    def __get_file_path():
        file_path = sys.argv[0].rsplit("/", 1)[0]
        if file_path.startswith("/"):
            return file_path

        return "./"

    def __make_pid_file(self):

        pid_path = os.path.join(self.__base_path, self.__pid_file_name)
        self.log.info("pid文件路径: pid_path = {}".format(pid_path))
        if os.path.exists(pid_path):
            with open(pid_path) as fp:
                pid = fp.read()
            if pid:
                pid = int(pid)
                if psutil.pid_exists(pid):
                    self.log.info("{} process running".format(self.__file_name))
                    os._exit(0)
        with open(pid_path, 'w') as pfile:
            pfile.write(str(os.getpid()))
        self.log.info("{} 启动成功...".format(self.__file_name))
        return pid_path

    def __del_pid_file(self):
        pid_path = os.path.join(self.__base_path, self.__pid_file_name)
        if os.path.exists(pid_path):
            os.remove(pid_path)
            self.log.info("删除pid文件成功: pid_path = {}".format(pid_path))
